<template>
<div class="search-suggestion">
  <van-cell
    v-for="(item,index) in suggestions"
    :key="index"
    icon="search"
    @click="$emit('search',item)"
    >
    <div slot="title" v-html="hightLine(item)"></div>
  </van-cell>



</div>
</template>

<script>
import {getSearchSuggestion } from '@/api/search'
import {debounce} from 'lodash'
export default {
name: "search-suggestion",
  data(){
  return{

    suggestions:[],
    strHtml:''

  }
  },
  props:{

    searchText:{
      typeof :String,
      required:true

}

  },
  watch:{
    searchText:{//这个是prop的属性，监听这个属性
      immediate:true, //一上来就监听

      // handler(value){ //这个是内置的一个方法
      //   this.getSearchSuggestion(value)
      // }
      //加入防抖
      handler:debounce(function (value){
        this.getSearchSuggestion(value)
      },1000)

    }
  },

  methods:{
//获取搜索建议
  async getSearchSuggestion(q){
    try {
     const {data} = await  getSearchSuggestion(q)
      this.suggestions=data.data.options
    }catch (err){
      this.$toast('数据获取失败，请稍后重试')
    }

  },

    hightLine(item){
    const hightStr=`<span style="color:red!important; ">${this.searchText}</span>`
      const reg=new RegExp(this.searchText,'gi')
   return  item.replace(reg,hightStr)


    }

  }
}
</script>

<style scoped>

</style>
